<template>
  <div class="task_form_dialog">
    <!-- 新建/编辑待办弹框 -->
    <el-dialog
      v-model="visible"
      :title="`${isDisableEditer ? '查看' : isEdit ? '编辑' : '新建'}待办`"
      :append-to-body="true"
      :show-close="false"
      :close-on-click-modal="false"
      top="3vh"
      center
      width="1000px"
    >
      <div v-loading="dialogLoading" class="dialog_container">
        <div class="form_box f_1">
          <el-form
            ref="formRef"
            :rules="rules"
            :model="form"
            label-width="75px"
            size="small"
          >
            <el-form-item label="标题：" prop="title">
              <div v-if="isDisableEditer" class="todo_title">
                {{ form.title }}
              </div>
              <el-input
                v-else
                v-model="form.title"
                size="small"
                maxlength="100"
                placeholder="请输入"
              ></el-input>
            </el-form-item>

            <el-form-item label="内容：" prop="content">
              <div v-if="isDisableEditer" v-html="form.content"></div>
              <!-- 富文本 -->
              <RichEditor
                v-else
                v-model:modelValue="form.content"
                :height="265"
                :businessKey="config.businessKey.TODO.val"
              />
            </el-form-item>

            <el-form-item label="时间：" prop="todoTime">
              <div v-if="isDisableEditer" class="todo_time">
                {{ form.todoTime }}
              </div>
              <el-date-picker
                v-else
                v-model="form.todoTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="选择日期"
                size="small"
              ></el-date-picker>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <template #footer>
        <div class="dialog_footer">
          <el-button
            v-if="!isDisableEditer"
            type="primary"
            @click="handleConfirm"
            :loading="confirmBtnLoading"
            size="small"
          >
            保存
          </el-button>
          <el-button @click="close" size="small">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, getCurrentInstance } from "vue";
import { ElMessage } from "element-plus";
import { useStore } from "vuex";
import RichEditor from "../../../components/RichEditor.vue";
import config from "../../../config";

const initFormData = () => {
  return {
    id: null,
    title: null,
    content: "",
    todoUserId: null,
    isFinish: "0",
    type: null,
    todoTime: null,
  };
};

export default {
  name: "TodoFormDialog",
  components: { RichEditor },
  props: {
    // 预加载数据
    prepareData: {
      type: Object,
      default: () => {
        return {
          isFinishSelectList: [],
        };
      },
    },
  },
  setup(props, context) {
    const { proxy } = getCurrentInstance();
    const $api = proxy.$api;
    const $moment = proxy.$moment;
    const store = useStore();

    const userInfo = computed(() => store.state.user.userInfo);

    const isEdit = ref(false);
    const isDisableEditer = ref(false);
    // 弹框是否显示
    const visible = ref(false);
    // 是否开启整个弹框loading（开启时无法关闭弹框）
    const dialogLoading = ref(false);
    // 确认按钮loading（开启时可以关闭弹框）
    const confirmBtnLoading = ref(false);
    // 表单的引用
    const formRef = ref(null);
    // 表单数据
    const form = reactive(initFormData());
    // 表单校验规则
    const rules = reactive({
      title: [{ required: true, message: "请输入待办标题", trigger: "blur" }],
      todoTime: [
        { required: true, message: "请选择待办时间", trigger: "blur" },
      ],
    });

    const handleConfirm = () => {
      formRef.value.validate((valid) => {
        if (valid) {
          confirmBtnLoading.value = true;
          $api.todo
            .saveOrUpdate(form)
            .then((res) => {
              confirmBtnLoading.value = false;
              ElMessage.success("操作成功！");
              // 触发事件，把数据传递给父组件
              context.emit("refresh");
              close();
            })
            .catch((err) => {
              confirmBtnLoading.value = false;
              console.error("saveOrUpdate error: ", err);
            });
        }
      });
    };

    // 填充默认数据（新建）
    const fillDefaultData = () => {
      form.todoUserId = userInfo.value.id;
      form.todoTime = $moment().format("YYYY-MM-DD");
    };

    // 打开弹框
    const open = (row, isDisabled = false) => {
      if (row) {
        Object.keys(form).forEach((item) => {
          form[item] = row[item];
        });
        isEdit.value = true;
      } else {
        isEdit.value = false;
        // if (!props.prepareData.isFinishSelectList) {
        //   return ElMessage.warning("关键数据未获取到，请关闭重新打开页面");
        // }
        fillDefaultData();
      }
      // console.log("open ===> isDisabled", isDisabled);
      isDisableEditer.value = isDisabled;
      visible.value = true;
    };

    // 关闭弹框
    const close = () => {
      if (confirmBtnLoading.value || dialogLoading.value) {
        return;
      }
      resetData();
      visible.value = false;
    };

    // 重置数据
    const resetData = () => {
      // 重置表单校验
      formRef.value && formRef.value.resetFields();
      // 重置表单数据
      Object.keys(form).forEach((item) => {
        form[item] = initFormData()[item];
      });
    };

    return {
      visible,
      dialogLoading,
      confirmBtnLoading,
      formRef,
      form,
      rules,
      open,
      close,
      handleConfirm,
      isEdit,
      isDisableEditer,
      config,
    };
  },
};
</script>

<style lang="less" scoped>
.todo_title {
  font-size: 18px;
  // font-weight: 600;
  color: #333;
}

.todo_time {
  font-size: 16px;
  color: #e6a23c;
}
</style>
